package xps.and.uudaijia.userclient.view.fragment;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.jude.utils.JUtils;
import com.zhy.autolayout.AutoFrameLayout;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import xps.and.uudaijia.userclient.App;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.util.AnimUtil;

public class MapViewFragment extends Fragment implements BaiduMap.OnMapStatusChangeListener, View.OnClickListener, BDLocationListener, OnGetGeoCoderResultListener, OnGetRoutePlanResultListener {
    String TAG = getClass().getSimpleName();
    @BindView(R.id.bmapView)
    public MapView mapView;
    @BindView(R.id.iv_pin)
    ImageView iv_pin;
    @BindView(R.id.iv_location)
    ImageView iv_location;
    BaiduMap baiduMap;
    LocationClient mLocationClient;
    GeoCoder geoCoder;
    RoutePlanSearch mRoutePlanSearch;
    boolean endmarkclickable = true;
    LatLng startLatlng = null;
    LatLng endLatlng = null;
    private BaiduMap mBaiduMap;
    ArrayList<PoiInfo> pois = new ArrayList<>();
    PinActivationListener pinActivonListener;

    Overlay markerOverlay;
    ObjectAnimator upAnimator = AnimUtil.getTransUpYAnim();
    ObjectAnimator downAnimator = AnimUtil.getTranDownYAnim();
    LatLng currentLatlng = null;
    int pinVisible = View.VISIBLE;
    Unbinder unbinder;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };

    int span = 0;
    int locaTime = 0;
    int spanHG = 0;
    int locaTimeHG = 0;
    /**
     * 允许路径规划
     */
    boolean ableroutePlane = true;

    public void clearOverlay(View view) {
        baiduMap.clear();
        markerOverlay = null;
    }

    public void setAbleroutePlane(boolean ableroutePlane) {
        this.ableroutePlane = ableroutePlane;
    }

   /* void onClickMarker() {

        mBaiduMap = mapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(14.0f);
        mBaiduMap.setMapStatus(msu);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                final MapBean beans = (MapBean) marker.getExtraInfo().get("BEAN");
                MapBean.ReturnBodyBean returnBodyBean = (MapBean.ReturnBodyBean) beans.getReturn_body();
                JUtils.Toast(returnBodyBean.getEntity_name());
                return false;
            }
        });
    }*/

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.map_fragment, null);
        unbinder = ButterKnife.bind(this, view);
        initView();
        //onClickMarker();
        Marker();
        return view;
    }

    public void setMarkClickable(boolean b) {
        endmarkclickable = b;
    }

    /**
     * 改变定位按钮的参数
     */
    public void resetLocationBtMargin(int right, int bottom) {
        AutoFrameLayout.LayoutParams layoutParams = new AutoFrameLayout.LayoutParams(AutoFrameLayout.LayoutParams.MATCH_PARENT, AutoFrameLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 0, right, bottom);
        layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
        layoutParams.width = 100;
        layoutParams.height = 100;
        iv_location.setLayoutParams(layoutParams);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        iv_pin.setVisibility(pinVisible);
    }

    /**
     * 更改地图中心大头针的可见性
     * 在onActivityCreated之后才会生效
     */
    public void setPinVisibility(int v) {
        pinVisible = v;
    }

    public int getPinVisable() {
        return iv_pin.getVisibility();
    }

    void initView() {
        setUpMap();
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(this);
        upAnimator.setTarget(iv_pin);
        downAnimator.setTarget(iv_pin);
        iv_location.setOnClickListener(this);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                BDLocation bdlocation = App.getInstance().getGloPosinfo().bdLocation;
                if (bdlocation != null) {
                    LatLng latlng = new LatLng(bdlocation.getLatitude(), bdlocation.getLongitude());
                    if (geoCoder != null)
                        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latlng));
                }
            }
        }, 500);

    }

    public void hide() {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.hide(this);
        fragmentTransaction.commit();
    }

    /**
     * note: 在activity销毁时传入null以免造成内存泄漏
     */
    public void setPinActionListener(PinActivationListener p) {
        pinActivonListener = p;
    }

    void setUpMap() {
        mapView.showZoomControls(false);
        mapView.showScaleControl(false);
        baiduMap = mapView.getMap();
        baiduMap.getUiSettings().setCompassEnabled(false);
        baiduMap.getUiSettings().setZoomGesturesEnabled(true);
        baiduMap.getUiSettings().setOverlookingGesturesEnabled(false);
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setViewPadding(35, 0, 20, 50);
        baiduMap.setOnMapStatusChangeListener(this);
        baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null));
        mLocationClient = new LocationClient(App.getInstance());
        mLocationClient.registerLocationListener(this);
        mRoutePlanSearch = RoutePlanSearch.newInstance();
        mRoutePlanSearch.setOnGetRoutePlanResultListener(this);
        periodLocation();
    }

    //一次性定位的配置
    private void singleLocation() {
        Log.e("MapViewFragment", "singleLocation");
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(span);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);

        option.setLocationNotify(true);
        option.setIsNeedLocationDescribe(true);
        option.setIsNeedLocationPoiList(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    //周期性定位的配置
    public void periodLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        int span = 1000 * 5;
        option.setScanSpan(span);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setLocationNotify(false);
        option.setIsNeedLocationDescribe(true);
        option.setIsNeedLocationPoiList(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }


    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

        if (iv_pin.getVisibility() == View.VISIBLE)
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (pinActivonListener != null)
                        pinActivonListener.onPinMoveStart();
                    if (downAnimator.isRunning()) return;
                    downAnimator.start();
                }
            });
    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {
        if (iv_pin.getVisibility() != View.VISIBLE) return;

        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(mapStatus.target));

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (upAnimator.isRunning()) return;
                upAnimator.start();
            }
        });
    }

    /**
     * 添加一个marker 在map上
     */
    public void addMarker(LatLng lat, String str) {
        LatLng point = lat;
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.qc_img);

        OverlayOptions option = new MarkerOptions()
                .position(point)
                .title(str)
                .icon(bitmap);
        markerOverlay = baiduMap.addOverlay(option);
    }

    /**
     * 添加一个marker 在map上
     */
    public void addMarkerMl(LatLng lat, String str) {
        LatLng point = lat;
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.qcml_img);

        OverlayOptions option = new MarkerOptions()
                .position(point)
                .title(str)
                .icon(bitmap);
        markerOverlay = baiduMap.addOverlay(option);
    }

    public void Marker() {
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Log.e("marker", "asdasd" + marker.getTitle().toString() + "");
                if (!marker.getTitle().toString().equals("")) {
                    JUtils.Toast(marker.getTitle());
                }
                return true;
            }
        });
    }

    /*
     * 添加一个marker 在map上
     */
    public void addMarker(LatLng lat, int resId, String str) {
        LatLng point = lat;
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(resId);
        JUtils.Toast(str);
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .title(str)
                .icon(bitmap);
        markerOverlay = baiduMap.addOverlay(option);
    }

    /**
     * 规划路径  ableroutePlan
     */
    void startRoutePlan() {
        if (null != startLatlng && null != endLatlng && ableroutePlane) {
            baiduMap.clear();

            mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
                    .from(PlanNode.withLocation(startLatlng))
                    .to(PlanNode.withLocation(endLatlng)));

        }
    }

    /**
     * 获取当前兴趣点列表
     */
    public ArrayList<PoiInfo> getPois() {
        return pois;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_location:
                recoveryCameraHG();
                break;
        }
    }

    /**
     * 让移动镜头回当前位置
     */
    public void recoveryCamera() {
        if (currentLatlng != null)
            moveCameraTo(currentLatlng);
    }

    /**
     * 让移动镜头回当前位置
     */
    public void recoveryCameraHG() {
        if (currentLatlng != null)
            moveCameraToHG(currentLatlng);
    }


    @Override
    public void onReceiveLocation(BDLocation location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        //保证这个方法只会被调用一次
        if (span == 0 && locaTime == 0) {
            Log.e("onReceiveLocation", "location");
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(1)
                    .direction(location.getDirection()).latitude(latLng.latitude)
                    .longitude(latLng.longitude).build();
            baiduMap.setMyLocationData(locData);
            moveCameraTo(latLng);
            currentLatlng = latLng;
            locaTime++;
        }
        currentLatlng = latLng;
    }

    @Override
    public void onConnectHotSpotMessage(String s, int i) {

    }

    /**
     * 在定位方法返回定位结果时调用
     * <p>
     * 把定位返回的Poi信息 转换成 PoiInfo 传到 pinActivonListener
     *
     * @param location 百度定位返回信息
     */
    void poiToPoiInfo(BDLocation location) {
        if (location == null || location.getPoiList() == null || location.getPoiList().size() <= 0)
            return;
        Poi poi = location.getPoiList().get(0);
        PoiInfo poiInfo = new PoiInfo();
        poiInfo.name = poi.getName();
        ArrayList<PoiInfo> pois = new ArrayList<>();
        pois.add(poiInfo);
        if (pinActivonListener != null)
            pinActivonListener.onPinMoved(pois);
    }

    /**
     * 移动镜头到指定经纬度
     *
     * @param latLng 坐标点
     */
    public void moveCameraTo(LatLng latLng) {
        MapStatus mMapStatus = new MapStatus.Builder().target(latLng
        ).zoom(20).build();
        MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        baiduMap.animateMapStatus(u);
    }
    /**
     * 移动镜头到指定经纬度
     *
     * @param latLng 坐标点
     */
    public void moveCameraToHG(LatLng latLng) {
        MapStatus mMapStatus = new MapStatus.Builder().target(latLng
        ).zoom(20).build();
        span = 0;
        Log.e("onReceiveLocation", "moveCameraToHG");
        locaTime = 0;
        MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        baiduMap.animateMapStatus(u);
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        onMapDestory();
        unbinder.unbind();
    }

    void onMapDestory() {
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();
        mLocationClient.unRegisterLocationListener(this);
        geoCoder.destroy();
        mRoutePlanSearch.destroy();

        geoCoder = null;
        baiduMap = null;
        mapView = null;
        mLocationClient = null;
        mRoutePlanSearch = null;
    }

    /**
     * 路径概览
     * */
//    void onStartRouteOverView() {
//        scaleAnimator.start();
//        startRoutePlan();
//    }

    /**
     * 设置起始位置
     *
     * @param poiI 起始地的poi信息
     */
    public void locat_startPoint(LatLng poiI) {
        LatLng latLng = poiI;
        startLatlng = latLng;
        startRoutePlan();
    }

    /**
     * 设置终点位置 @see MapViewFragment.locat_startPoint();
     */
    public void locat_endPoint(LatLng poiI) {
        LatLng latLng = poiI;
        this.endLatlng = latLng;
        startRoutePlan();
    }

    public LatLng getStartLatlng() {
        return this.startLatlng;
    }

    public LatLng getEndLatlng() {
        return this.endLatlng;
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) return;
        if (null == result.getPoiList() || result.getPoiList().size() <= 0) return;

        pois.clear();
        pois.addAll(result.getPoiList());
        if (pinActivonListener != null)
            pinActivonListener.onPinMoved(pois);

    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
//        if (drivingRouteResult == null || drivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR)
//            return;
//
//        if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
//
//            if (drivingRouteResult.getRouteLines().size() >= 1) {
//                DrivingRouteLine drivingRouteLine = drivingRouteResult.getRouteLines().get(0);//使用推荐的第一条路线
//                HSSDrivingRouteOverlay overlay = new HSSDrivingRouteOverlay(baiduMap, getActivity());
//                overlay.getTerminalMarker();
//                overlay.setData(drivingRouteLine);
//                overlay.addToMap();
//                overlay.zoomToSpan();
//
//            }
//        }
    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }


    public interface PinActivationListener {
        /**
         * 当地图停止移动时调用
         */
        void onPinMoved(ArrayList<PoiInfo> p);

        /**
         * 在地图开始移动时调用
         */
        void onPinMoveStart();
    }

    public void resetOverlay() {
        clearOverlay(null);
    }

}